package com.tdx.blog_nowcoder.service;

import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @description: TODO
* @author 何可人
* @date 2022/7/10 16:40
* @version 1.0
*/

@Service
public class WebDataVistorsService {  // 网站数据统计
    @Autowired
    private RedisTemplate redisTemplate;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    // 记录访问的IP
    public void recordUV(String ip){
        String uvkey = RedisKeyUtils.getUVKey(sdf.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvkey,ip);
    }

    // 统计指定日期范围内的UV
    public Long calculateUV(Date start,Date end){
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        List<String> redisKeyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);

        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtils.getUVKey(sdf.format(calendar.getTime()));
            redisKeyList.add(key);
            calendar.add(Calendar.DATE, 1);
        }
        //合并
        // 合并这些数据 新的redisKey保存
        String redisKey = RedisKeyUtils.getUVKey(sdf.format(start), sdf.format(end));
        redisTemplate.opsForHyperLogLog().union(redisKey,redisKeyList.toArray());
      // 返回统计的结果
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }


    // 记录单日活跃用户的ID
    public void recordDAU(int userId){
        String duvkey = RedisKeyUtils.getDAUKey(sdf.format(new Date()));
        redisTemplate.opsForValue().setBit(duvkey,userId,true);
    }


    // 统计指定日期范围内的DAU
    public long calculateDAU(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 整理该日期范围内的key
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String key = RedisKeyUtils.getDAUKey(sdf.format(calendar.getTime()));
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        // 进行OR运算
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtils.getDAUKey(sdf.format(start), sdf.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        redisKey.getBytes(), keyList.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes());
            }
        });
    }


}
